module source.sharedmemory;

import std.mmfile : MmFile;
import std.conv : to;

class SHMmanager
{
    public MmFile location;
    private ulong length;

    this(string filename, ulong size, size_t blocksize, MmFile.Mode accessMode = MmFile.Mode.readWrite)
    {
        this.location = new MmFile(filename, accessMode, size, null, blocksize);
        this.length = location.length;
    }

    public string getContents()
    {
        string output;
        for (ulong i = 0; i < this.length; i++)
        {
            if (this.location.opIndex(i) != 0)
            {
                output ~= this.location.opIndex(i);
            }
        }
        return output;
    }

    public void appendContents(string content)
    {
        string current = this.getContents();
        current ~= content ~ "\n";
        this.writeContents(current);
    }

    public string deleteFirst()
    {
        string output;
        string newContent;

        for (ulong i = 0; i < this.length; i++)
        {
            if (this.location.opIndex(i) == 10)
            {
                output = to!string(this.location[0 .. i+1]);
                newContent = to!string(this.location[i+1 .. this.length]);
                break;
            }
        }
        this.writeContents(newContent);
        return output;
    }

    public bool isEmpty()
    {
        if (this.location.opIndex(0) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private void writeContents(string contents)
    {
        ubyte[] toWrite = cast(ubyte[])contents;
        foreach (ulong index, ubyte write; toWrite)
        {
            this.location.opIndexAssign(write, index);
        }
    }
}
